package com.yh.tea.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yh.tea.entity.UserRole;
import com.yh.tea.model.UserQuery;
import com.yh.tea.model.UserRoleQuery;
import com.yh.tea.service.UserRoleService;
import com.yh.tea.utiity.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yh
 * @since 2024-02-16
 */
@RestController
@CrossOrigin
@RequestMapping("/userRole")
public class UserRoleController {
    @Autowired
    private UserRoleService userRoleService;
    @PostMapping("/getRoleIdByUserId")
    public ResponseResult getRoleIdByUserId(@RequestBody UserRole userRole){
        return userRoleService.getRoleIdByUserId(userRole.getUserId());
    }
    /***
     *分页查寻
     */
    @PostMapping("/pageList")
    public ResponseResult pageList(@RequestBody UserRoleQuery userRoleQuery){
        return userRoleService.pageList(userRoleQuery);
    }
    /***
     * 修改角色
     */
    @PostMapping("/updateRole")
    public ResponseResult updateRole(@RequestBody UserRole userRole){
        Boolean result=userRoleService.updateById(userRole);
        return ResponseResult.success(result?"修改成功":"修改失败",result);
    }


    @PostMapping("/updateByRoleId")
    public ResponseResult updateByRoleId(@RequestBody List<Long> roleIds){
        Boolean result=false;
        if(roleIds!=null)
        for (Long roleId : roleIds) {
            UserRole userRole=userRoleService.getOne(new QueryWrapper<UserRole>().eq("role_id",roleId));
            if(userRole==null){
                return ResponseResult.success();
            }
            userRole.setRoleId(0L);
            result=userRoleService.update(userRole,new QueryWrapper<UserRole>().eq("role_id",roleId))||result;
        }
        return ResponseResult.success(result?"修改成功":"修改失败",result);
    }
    /***
     * 初始添加
     *
     */
    @PostMapping("/add")
    public ResponseResult add(@RequestBody UserRole userRole){
        Boolean result=userRoleService.save(userRole);
        return ResponseResult.success(result?"添加成功":"添加失败",result);
    }

    @PostMapping("/delByUserIds")
    public ResponseResult delByUserIds(@RequestBody List<Long> userIds){
        Boolean result=false;
        for (Long userId : userIds) {
          result = userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id",userId))||result;
        }

        return ResponseResult.success(result?"删除成功":"删除失败",result);
    }

}

